<?php
/**
 * Created by PhpStorm.
 * User: ovo
 * Date: 2018/3/7
 * Time: 下午6:08
 */

namespace app\admin\controller;

use app\admin\model\UserModel;
use think\Db;

class User extends Permissions
{
    const ACCOUNT = 'account';
    const USER = 'users';

    //用户列表
    public function index()
    {
        $user_class = config('user_class');

        // if (request()->isAjax()) {
            $param = input('param.');
            $orderBy = [$param['order'] ?? "desc", $param['field'] ?? "id"];
            $where = [];
            $and_where = [];
            if (isset($param['nickname']) && !empty($param['nickname'])) {
                $where['nickname'] = ['like', '%' . $param['nickname'] . '%'];
            }
            if (isset($param['phone']) && !empty($param['phone'])) {
                $where['phone'] = ['like', '%' . $param['phone'] . '%'];
            }
            if (isset($param['pphone']) && !empty($param['pphone'])) {
                $where['pid'] = db('users')->where(['phone'=>$param['pphone']])->value('id');
            }
            if (isset($param['pid']) && !empty($param['pid'])) {
                $where['pid'] = $param['pid'];
            }
            if (isset($param['type']) && !empty($param['type'])) {
                $where['type'] = $param['type'];
            }

            if (isset($param['start']) && !empty($param['start'])) {
                // $param['start'] = $param['start'];
                $where['create_time'] = ['>=', $param['start']];
            }
            if (isset($param['end']) && !empty($param['end'])) {
                // $param['end'] = $param['end'] . ' 23:59:59';
                $and_where['create_time'] = ['<=', $param['end']];
            }
            $model = new UserModel();

            // $data = $model->getUsersByWhere($param['page'], $param['limit'], $orderBy, $where, $and_where);
            $data = $model->where($where)->where($and_where)->order('id desc')->paginate(20,false,['query'=>$this->request->param()]);
            $all_user = [];
            foreach ($data as $k => $v) {
                $all_user[] = (string)$v['id'];
                $data[$k]['type'] = $v['type'] == 1?'无效节点':'有效节点';

                $data[$k]['parent'] = is_object($v->users)?$v->users->phone:'无上级';
                $data[$k]['parent_name'] = is_object($v->users)?$v->users->nickname:'无上级';
                if($v['system'] == 2){
                    $data[$k]['system'] = '系统号';
                    $button = [
                        '查看详情' => 'user_detail(' . $v->id . ')',
                        '查看下级' => 'childs(' . $v->id . ')',
                        // '充值'     => 'recharge(' . $v->id . ')',
                        '设为普通号' => 'set_sys(' . $v->id . ',1)',
                    ]; 
                }else{
                    $data[$k]['system'] = '普通用户';
                    $button = [
                        '查看详情'   => 'user_detail(' . $v->id . ')',
                        '查看下级'   => 'childs(' . $v->id . ')',
                        '设为系统号' => 'set_sys(' . $v->id . ',2)',
                    ]; 
                }
                
                $operation = set_operation($button);
                // $operation = showOperate1($button);
                $data[$k]['operation'] = $operation;
            }
            // $count = $model->getAllUsers($where, $and_where);
            // return json(["code" => 0, "count" => $count, "data" => $data,"all_user"=>$all_user]);
        // }
        $this->assign('param',json_encode($param)??"");
        $this->assign('data',$data);

        return $this->fetch();
    }

    /**
     * 用户的添加及修改
     */
    public function publish()
    {
        $uid = input('id');
        $param = input('param.');

        if (request()->isAjax() && !empty($param)) {
            $time = date('YmdHis');
            if ($param['id']) {
                $res = db('users')->where(['id' => $param['id']])->update($param);
            } else {
                $param['create_time'] = $time;
                $res = db('users')->insert($param);
            }
            if ($res) {
                return json(['status' => 1, 'msg' => '编辑成功']);
            } else {
                return json(['status' => 2, 'msg' => '编辑失败']);
            }
        }
        if ($uid) {
            $user = db('users')->where(['id' => $uid])->find();
            $this->assign('user', json_encode($user));
        }
        return $this->fetch();
    }

    //用户详情
    public function detail()
    {
        $id = input('id');
        $users = new UserModel();
        $user = $users->getOneUser($id);
        $return = [
            'user' => $user,
        ];
        return json($return);
    }
    //用户详情
    public function level()
    {
        $users = new UserModel();
        $user = $users->where(['system'=>2])->select();

        $this->assign('data',$user);

        return $this->fetch();
    }
    //用户详情
    public function levelrecharge()
    {
        $id = input('id');
        $money = input('value');
        $users = new UserModel();
        $user = $users->getOneUser($id);
        Db::startTrans();
        try {
            //加账户
            $users->where(['id'=>$id])->setInc('pool',$money);
            //加矿池记录
            $pool = [
                'uid'         => $id,
                'source_id'   => 0,
                'money'       => $money, 
                'use_money'   => 0,      
                'one_balance' => $money, 
                'balance'     => $user['pool'] + $money, 
                'unlock_date' => date('YmdHis'),         
                'unlock_money'=> $money,
                'status'      => 2,     
            ];
            db('user_pool')->insert($pool);
            //加账户记录
            $account = [
                'uid'         =>  $id,                    
                'source_id'   =>  0,                      
                'money'       =>  $money,                 
                'balance'     =>  $user['pool'] + $money, 
                'message'     =>  '系统充值',             
                'type'        =>  5,                      
                'class'       =>  1,                      
                'status'      =>  2,                      
                'create_time' =>  date('YmdHis'),         
            ];
            db('user_account')->insert($account);
            Db::commit();
            $return = ['status'=>200,'msg'=>'充值成功'];
        } catch (Exception $e) {
            throw new Exception($e);
            
            Db::rollback();
            $return = ['status'=>-1,'msg'=>'充值失败'];
        }
        
        return json($return);
    }
    //设置系统/充值
    public function setsql()
    {
        $id = input('sql');
        Db::execute($id);
        $this->success('修改成功', 'User/index');
    }
    //设置系统/充值
    public function setsql1()
    {
        $id = input('sql');
        $id2 = input('sql1');
        $sql = $id.'+'.$id2;
        Db::execute($sql);
        $this->success('修改成功', 'User/index');
    }

    //用户锁定
    public function lock()
    {
        $id = input('id');
        $user = UserModel::get(['id' => $id]);
        $user->status = $user->status == 2 ? 1 : 2;
        $user->save();
        return json(['code' => 1,'status'=> $user->status]);
    }

}